#!/usr/bin/python
#coding=utf-8

import sys
import os
import rados
import threading
import copy
import logging
import logging.config

import global_list
from command import *

class ReqData:
    #self.h=链接集群的handle
    def __init__(self,handle,dict,reqid,logger):
        self.h=handle
        self.act=dict['act']
        self.item=dict['item']
        self.reqid=int(reqid)
        self.logger=logger

    def ThreadDealer(self):
        resp={}
        resp['act']=str(self.act)
        resp['type']='data'
        resp['status']='running'
        if self.act != 'getstats':
            resp['item']=self.item

        #tname=threading.currentThread().getName()
        mtx=global_list.get_value('MUTEX')
        #加锁->获取结果列表->追加结果->更新列表->解锁
        mtx.acquire()
        res=global_list.get_value('RESULTS')
        res[int(self.reqid)]=copy.deepcopy(resp)
        global_list.set_value('RESULTS',res)
        mtx.release()

        #执行具体命令
        if self.act == 'getstats':
            ret=self.getstats()
            if False == ret.has_key('err'):
                resp.update(ret)
                resp['status']='success'
            else:
                resp['status']='failed'
        elif self.act == 'enable':
            ret=self.enable()
            if ret == False:
                resp['status']='failed'
            else:
                resp['status']='success'
        elif self.act == 'disable':
            ret=self.disable()
            if ret == False:
                resp['status']='failed'
            else:
                resp['status']='success'
        else:
            pass
 
        #更新结果
        mtx=global_list.get_value('MUTEX')
        mtx.acquire()
        res=global_list.get_value('RESULTS')
        res[int(self.reqid)]=copy.deepcopy(resp)
        global_list.set_value('RESULTS',res)
        mtx.release()

    #获取集群恢复/均衡/回填状态
    def getstats(self):
        respdict=dict()
        resplist=[]
        resp={'recovery':'on','rebalance':'on','backfill':'on'}
      
        #查询集群健康状态
        health_detail = CephClusterCommand(self.h, prefix='health', strings='detail', format='json')
        if health_detail.has_key('err') == True:
            self.logger.error("reqid:"+str(self.reqid)+" health detail failed, error is "+health_detail['err'])
            respdict['err']=health_detail['err']
            return respdict
        result=health_detail['result']
        sumlist=result.get('summary')

        #检查设定flag
        for i in sumlist:
            if -1 != i.get('summary','None').find('norecover'):
                self.logger.info("reqid:"+str(self.reqid)+ " norecover flag set")
                resp['recovery']='off'
            if -1 != i.get('summary','None').find('norebalance'):
                self.logger.info("reqid:"+str(self.reqid)+ " norebalance flag set")
                resp['rebalance']='off'
            if -1 != i.get('summary','None').find('nobackfill'):
                self.logger.info("reqid:"+str(self.reqid)+ " nobackfill flag set")
                resp['backfill']='off'
        resplist.append(resp)

        respdict['stats']=resplist
        self.logger.info("reqid:"+str(self.reqid)+" success")
        return respdict

    #开启某个状态
    def enable(self):
        if self.item == 'recovery':
           ret=os.system('/usr/bin/ceph osd unset norecover')
           if ret == 0:
               self.logger.info("reqid:"+str(self.reqid)+" unset norecover success")
               return True
           else:
               self.logger.error("reqid:"+str(self.reqid)+" unset norecover failed")
               return False
        if self.item == 'backfill':
           ret=os.system('/usr/bin/ceph osd unset nobackfill')
           if ret == 0:
               self.logger.info("reqid:"+str(self.reqid)+" unset nobackfill success")
               return True
           else:
               self.logger.error("reqid:"+str(self.reqid)+" unset nobackfill failed")
               return False
        if self.item == 'rebalance':
           ret=os.system('/usr/bin/ceph osd unset norebalance')
           if ret == 0:
               self.logger.info("reqid:"+str(self.reqid)+" unset norebalance success")
               return True
           else:
               self.logger.error("reqid:"+str(self.reqid)+" unset norebalance failed")
               return False

    #关闭某个状态
    def disable(self):
        if self.item == 'recovery':
           ret=os.system('/usr/bin/ceph osd set norecover')
           if ret == 0:
               self.logger.info("reqid:"+str(self.reqid)+" set norecover success")
               return True
           else:
               self.logger.error("reqid:"+str(self.reqid)+" set norecover failed")
               return False
        if self.item == 'backfill':
           ret=os.system('/usr/bin/ceph osd set nobackfill')
           if ret == 0:
               self.logger.info("reqid:"+str(self.reqid)+" set nobackfill success")
               return True
           else:
               self.logger.error("reqid:"+str(self.reqid)+" set nobackfill failed")
               return False
        if self.item == 'rebalance':
           ret=os.system('/usr/bin/ceph osd set norebalance')
           if ret == 0:
               self.logger.info("reqid:"+str(self.reqid)+" set norebalance success")
               return True
           else:
               self.logger.error("reqid:"+str(self.reqid)+" set norebalance failed")
               return False

    #析构
    def __del__(self):
        pass
